package org.kpli.jak.db.third;

import java.util.Iterator;
import java.util.List;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

/**
 * 
 * @author dendy
 * 
 */

public class OpenShell {

	private Display display;

	private Shell shell = null;

	private Label labelID, labelName, labelAlamat;

	private Text textID, textName, textAlamat;

	private Button buttonSave, buttonUpdate, buttonDelete;

	private Table table;

	private Group group = null;

	private Composite composite = null;

	SessionFactory sessionFactory;

	Session session;

	public OpenShell() {
		sessionFactory = new Configuration().configure().buildSessionFactory();
	}

	public void run() {
		groupManager();
		fillTable();

		shell.open();
		while (!shell.isDisposed())
			if (!display.readAndDispatch())
				display.sleep();

		display.dispose();
	}

	private void groupManager() {

		display = new Display();
		shell = new Shell(display);
		shell.setText("Hibernate CRUD Sample using SWT");

		shell.setLayout(new GridLayout(2, false));

		// Membuat grup pada tampilan
		group = new Group(shell, SWT.NONE);
		group.setLayout(new GridLayout(2, false));
		group.setLayoutData(new GridData(GridData.FILL_BOTH));

		// Menampilkan label ID dan compositenya
		labelID = new Label(group, SWT.NONE);
		labelID.setText("ID");
		textID = new Text(group, SWT.BORDER);

		// Menampilkan label nama dan compositenya
		labelName = new Label(group, SWT.NONE);
		labelName.setText("Name");
		textName = new Text(group, SWT.BORDER);

		// Menampilkan label email dan compositenya
		labelAlamat = new Label(group, SWT.NONE);
		labelAlamat.setText("Address");
		textAlamat = new Text(group, SWT.BORDER);

		composite = new Composite(group, SWT.NONE);
		FillLayout fillButton = new FillLayout();
		fillButton.spacing = 5;
		composite.setLayout(fillButton);

		table = new Table(group, SWT.FULL_SELECTION | SWT.BORDER);
		table.setLinesVisible(true);
		table.setHeaderVisible(true);

		TableColumn columnID = new TableColumn(table, SWT.NONE);
		columnID.setText("ID");
		columnID.setWidth(40);

		TableColumn columnName = new TableColumn(table, SWT.NONE);
		columnName.setText("Name");
		columnName.setWidth(130);

		TableColumn columnAddress = new TableColumn(table, SWT.NONE);
		columnAddress.setText("Address");
		columnAddress.setWidth(150);

		// griddata label
		GridData gridDataLabel = new GridData();
		gridDataLabel.widthHint = 200;
		labelID.setLayoutData(gridDataLabel);
		labelName.setLayoutData(gridDataLabel);
		labelAlamat.setLayoutData(gridDataLabel);

		// griddata text
		GridData gridDataText = new GridData(GridData.FILL_HORIZONTAL);
		textID.setLayoutData(gridDataText);
		textName.setLayoutData(gridDataText);
		textAlamat.setLayoutData(gridDataText);

		// grid data table
		GridData gridDataTabel = new GridData(GridData.FILL_VERTICAL);
		gridDataTabel.horizontalSpan = 2;
		gridDataTabel.horizontalAlignment = GridData.CENTER;
		table.setLayoutData(gridDataTabel);

		// gridata button
		GridData gridDataButton = new GridData();
		gridDataButton.horizontalSpan = 2;
		gridDataButton.widthHint = 300;
		gridDataButton.horizontalAlignment = SWT.CENTER;
		composite.setLayoutData(gridDataButton);

		/** Button Save */
		buttonSave = new Button(composite, SWT.PUSH);
		buttonSave.setText("Save");
		buttonSave.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				if (event.getSource().equals(buttonSave)) {
					session = sessionFactory.openSession();
					Transaction transaction = session.beginTransaction();

					Person person = new Person();
					person.setId(textID.getText());
					person.setNama(textName.getText());
					person.setAlamat(textAlamat.getText());

					session.save(person);
					transaction.commit();
				} else {
					MessageBox msgbox = new MessageBox(shell,
							SWT.ICON_INFORMATION);
					msgbox.setText("Confirmation");
					msgbox.setMessage("Please fill all the fields!");
					msgbox.open();
				}

				fillTable();
				clearText();
			}
		});

		/** Button Update */
		buttonUpdate = new Button(composite, SWT.PUSH);
		buttonUpdate.setText("Update");
		buttonUpdate.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event1) {
				if (event1.getSource().equals(buttonUpdate)) {
					session = sessionFactory.openSession();

					Transaction transaction = session.beginTransaction();

					Person person = (Person) session.get(Person.class,
							new Long(table.getItem(table.getSelectionIndex())
									.getText(3)));

					person.setId(textID.getText());
					person.setNama(textName.getText());
					person.setAlamat(textAlamat.getText());

					session.save(person);
					transaction.commit();
				} else {
					MessageBox msgbox = new MessageBox(shell,
							SWT.ICON_INFORMATION);
					msgbox.setText("Confirmation");
					msgbox.setMessage("There's no data to update.");
					msgbox.open();
				}
				fillTable();
				clearText();
			}
		});

		/** Button Delete */
		buttonDelete = new Button(composite, SWT.PUSH);
		buttonDelete.setText("Delete");
		buttonDelete.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent ecent) {
				if (ecent.getSource().equals(buttonDelete)) {
					session = sessionFactory.openSession();

					Transaction transaction = session.beginTransaction();

					Person person = (Person) session.get(Person.class,
							new Long(table.getItem(table.getSelectionIndex())
									.getText(3)));

					session.delete(person);
					transaction.commit();
				} else {
					MessageBox msgbox = new MessageBox(shell,
							SWT.ICON_INFORMATION);
					msgbox.setText("Confirmation");
					msgbox.setMessage("There's no data to delete.");
					msgbox.open();
				}
				fillTable();
				clearText();
			}
		});

		table.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent arg0) {
				textID.setText(table.getItem(table.getSelectionIndex())
						.getText(0));
				textName.setText(table.getItem(table.getSelectionIndex())
						.getText(1));
				textAlamat.setText(table.getItem(table.getSelectionIndex())
						.getText(2));
				clearText();
			}
		});

		shell.setSize(380, 350);
	}

	private void fillTable() {

		session = sessionFactory.openSession();

		Transaction transaction = session.beginTransaction();

		Query query = session.createQuery("from Person");

		@SuppressWarnings("unchecked")
		List<Person> list = query.list();

		Iterator<Person> iterator = list.iterator();

		TableItem item;

		while (iterator.hasNext()) {
			try {
				Person person = iterator.next();
				item = new TableItem(table, SWT.NONE);
				item.setText(0, person.getId());
				item.setText(1, person.getNama());
				item.setText(2, person.getAlamat());
				transaction.commit();
				session.close();
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	private void clearText() {
		textID.setText("");
		textName.setText("");
		textAlamat.setText("");
	}
}
